package com.jinchange.mysqlandredis.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jinchange.mysqlandredis.entity.Person;
import com.jinchange.mysqlandredis.mapper.PersonMapper;
import com.jinchange.mysqlandredis.service.PersonService;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import javax.annotation.Resource;

/**
 * @ClassName: PersonServiceImpl
 * @Author zhangjin
 * @Date 2021/8/4 18:48
 * @Description: PersonServiceImpl 业务实现类继承 ServiceImpl 类生成增删改查基础业务方法
 */
@Service
@CacheConfig(cacheNames = {"person"})
public class PersonServiceImpl  extends ServiceImpl<PersonMapper, Person> implements PersonService {

    @Resource
    private PersonServiceImpl personService;

    @Resource
    private PersonMapper personMapper;

    @Override
    public Person addPerson(Person person) {
        Assert.isTrue( personService.save(person), "保存失败!");
        return person;
    }

    @Override
    @Cacheable(key = "#id",unless = "#id==null")
    public Person findPerson(Long id) {
        Person person;
        try {
            person = personService.getById(id);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("查找失败!");
        }
        return person;
    }

    @Override
    @CachePut(key = "#person.id", unless = "#person == null")
    public Person setPerson(Person person) {
        try {
            personService.updateById(person);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("更新失败");
        }
        return person;
    }

    @Override
    @CacheEvict(key = "#id")
    public boolean deletePerson(Long id) {
        try{
            Assert.isTrue(personService.removeById(id), "删除失败!");
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    @Override
    public IPage<Person> findPersonByPagination(Integer current, Integer size) {
        // 分页规则 search参数判断是否查询count 和 pages; 不查询适用于移动端下拉分页场景.
        Page<Person> personPage = new Page<>(current, size, true);
        // 条件构造器(无条件)
        LambdaQueryWrapper<Person> query = new LambdaQueryWrapper<Person>();
        return personMapper.selectPage(personPage, query);
    }

    @Override
    public IPage<Person> findPersonByNameOrAge(Page<Person> page, String name, Integer age) {
        return personMapper.findPersonByNameOrAge(page, name, age);
    }


}
